package cn.itsource.org.controller;

import cn.itsource.basic.utils.PageResult;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.EmployeeService;
import cn.itsource.basic.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
@Api(value = "员工的API",description="部门相关的CRUD功能")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //注意前端地址：http://localhost:8080/employee - get
    //查询所有
    @GetMapping
    @ApiOperation("查询所有")
    public List<Employee> findAll() {
        return employeeService.findAll();
    }

    //注意前端地址：http://localhost:8080/employee/1 - get
    //根据id查询
    @GetMapping("/{id}")
    @ApiOperation("根据id查询")
    public Employee findOne(@PathVariable("id") Long id) {
        return employeeService.findOne(id);
    }

    //注意前端地址：http://localhost:8080/employee/1 - delete
    //根据id删除
    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            employeeService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }


    //注意前端地址：http://localhost:8080/employee - put - {}
    @PutMapping
    @ApiOperation("添加修改")
    public AjaxResult addorUpdate(@RequestBody Employee employee) {
        try {
            if (employee.getId() == null) {//添加操作
                employeeService.add(employee);
            } else {
                employeeService.update(employee);
            }
            //如果成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //注意前端地址：http://localhost:8080/employee - Patch - []
    //批量删除
    @PatchMapping
    @ApiOperation("批量删除")
    public AjaxResult patchdel(@RequestBody Long[] ids) {
        try {
            employeeService.patchdel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //分页
    @PostMapping
    @ApiOperation("分页查询")
    public PageResult<Employee> queryPage(@RequestBody EmployeeQuery employeeQuery) {
        return employeeService.queryPage(employeeQuery);
    }

    /**
     * 获取当前店铺下的所有员工：店长或者店员
     * @param shopId
     * @return
     */
    @GetMapping("/list/{shopId}")
    public List<Employee> list(@PathVariable("shopId") Long shopId){
        return employeeService.findEmployeeByShopId(shopId);
    }
}
